<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebRTC Live Streaming</title>
</head>
<body>
    <h1>WebRTC Live Streaming</h1>
    <video id="localVideo" autoplay playsinline></video>
    <script src="/socket.io/socket.io.js"></script>
    <script>
        const localVideo = document.getElementById('localVideo');
        const socket = io();

        let localStream;
        let peerConnection;

        async function start() {
            localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
            localVideo.srcObject = localStream;

            peerConnection = new RTCPeerConnection({
                iceServers: [
                    { urls: 'stun:stun.l.google.com:19302' }
                ]
            });

            localStream.getTracks().forEach(track => {
                peerConnection.addTrack(track, localStream);
            });

            peerConnection.onicecandidate = event => {
                if (event.candidate) {
                    socket.emit('ice-candidate', event.candidate);
                }
            };

            peerConnection.ontrack = event => {
                const remoteVideo = document.createElement('video');
                remoteVideo.srcObject = event.streams[0];
                remoteVideo.autoplay = true;
                remoteVideo.playsinline = true;
                document.body.appendChild(remoteVideo);
            };

            const offer = await peerConnection.createOffer();
            await peerConnection.setLocalDescription(offer);
            socket.emit('offer', offer);
        }

        socket.on('answer', async (answer) => {
            await peerConnection.setRemoteDescription(new RTCSessionDescription(answer));
        });

        socket.on('ice-candidate', async (candidate) => {
            await peerConnection.addIceCandidate(new RTCIceCandidate(candidate));
        });

        start();
    </script>
</body>
</html>